
var schema = require("./schema");
var mongoose = schema.mongoose;
var donation = schema.donation;
var user = schema.user;

//generate the name of the target collection
var name = () => {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var name =  "_" + year + "_" + month + "s";

    return name
};

//insert a new donation record
var insert = (req, res) => {
    var name = name();
    var model = mongoose.model(name, donation);

    var document = new model({
        user: req.body.user,
        donation: req.body.donation,
        date: req.body.date
    });

    document.save((err, resin) => {
        if (err){
            console.log("error: " + err);
            res.end("0")
        }else{
            res.end("1")
        }
    });
};

//query for the donation records in the current month
var query_month = (req, res) => {
    var name = name();
    var model = mongoose.model(name, donation);

    model.find( {}, (err, document) => {
        res.end(document);
    });
};

//query for the global donation data : number of users, money in total
var query_data = (req, res) => {
    var users = mongoose.model("users", user);
    var num_users = 0;
    users.count((err, count) => {
        if(err) {
            console.log(err);
        }else{
            console.log(count);
            num_users = count;
        }
    });

    mongoose.connection.on('open', function (ref) {

        //trying to get collection names
        mongoose.connection.db.listCollections().toArray((function (err, names) {
            var col = null;
            var money = 0;
            for(var i = 0; i < names.length; i++){
                if(i == 0){
                    col = mongoose.model(names[i].name, user);
                }else{
                    col = mongoose.model(names[i].name, donation);
                }
                col.find((err, docs) => {
                    if(err) {
                        console.log(err);
                    }else{

                    }

                })

            }

        }));
    });


};

query_data();


module.exports = {
    insert: insert,
    query_month: query_month
};